import { defineStore } from 'pinia';
import  store  from '@/store';
import { ref } from 'vue';
import { loginApi, refreshApi } from '@/api';
import { LoginData, LoginResult, RefreshData } from '@/types/user';

export const useUserStore = defineStore('user', () => {
  //state

  const username = ref('');
  const token = ref('');
  const refreshToken = ref('');
  let refreshPromise: Promise<boolean>|null;
  async function login(loginData: LoginData) {
    console.log('login');
    let res: Result<LoginResult>;
    try {
      res = await loginApi(loginData);
      console.log(res);
      if (res.code === 1000) {
        username.value = loginData.username;
        token.value = res.data.token;
        refreshToken.value = res.data.refreshToken;
      }
      return res;
    } catch (e) {
      console.log(e);
    }
    return null;
  }
  async function refresh() {
    console.log('refresh');
    if (refreshPromise) {//防止重复刷新
      return refreshPromise;
    }
    refreshPromise = new Promise(async (resolve) => {
      let flag = false;
      try {
        const refreshData: RefreshData = { refreshToken: refreshToken.value };
        const res: Result<LoginResult> = await refreshApi(refreshData);
        if (res.code === 1000) {
          flag = true;
          token.value = res.data.token;
          refreshToken.value = res.data.refreshToken;
        }
      } catch (e) {
        console.log(e);
      }
      resolve(flag);
    });
    refreshPromise.finally(() => {
      refreshPromise = null;
    });
    return refreshPromise;
  }
  function isRefresh(config: any) {
    return !!config.__isRefresh;
  }
  return {
    username,
    token,
    refreshToken,
    login,
    refresh,
    isRefresh
  };
});

// 非setup 在其他ts中引用
// 直接用useUserStoreHook().username 不要使用 const userStore = useUserStoreHook(); useUserStore 还未定义初始化
export  function useUserStoreHook() {
  return useUserStore(store);
}
